#include "customprocessbae.h"
#include <QMouseEvent>
#include <QStyle>
#include <QStyleOptionProgressBar>
#include <QDebug>

CustomProgressBar::CustomProgressBar(QWidget *parent)
    : QProgressBar(parent)
{
    setMouseTracking(false);
}

// 设置整数百分比 (0-100)
void CustomProgressBar::setPercentage(int percentage)
{
    // 确保百分比在有效范围内
    percentage = qMax(0, qMin(100, percentage));

    // 计算对应的值
    int range = maximum() - minimum();
    int newValue = minimum() + (percentage * range) / 100;

    setValue(newValue);

    // 发射百分比变化信号
    emit percentageChanged(percentage);
    // qDebug() << "Progress set to:" << percentage << "%";
}

// 设置浮点数百分比 (0.0-100.0)
void CustomProgressBar::setPercentage(double percentage)
{
    // 确保百分比在有效范围内
    percentage = qMax(0.0, qMin(100.0, percentage));

    // 计算对应的值
    double range = static_cast<double>(maximum() - minimum());
    int newValue = minimum() + static_cast<int>((percentage * range) / 100.0);

    setValue(newValue);

    // 发射百分比变化信号
    emit percentageChanged(static_cast<int>(percentage)); // 整数信号
    emit percentageChanged(percentage); // 浮点数信号
    // qDebug() << "Progress set to:" << percentage << "% (precise)";
}

// 获取当前百分比（整数）
int CustomProgressBar::getPercentage() const
{
    if (maximum() == minimum()) return 0; // 避免除零

    int range = maximum() - minimum();
    int currentValue = value() - minimum();

    return (currentValue * 100) / range;
}

// 获取当前精确百分比（浮点数）
double CustomProgressBar::getPrecisePercentage() const
{
    if (maximum() == minimum()) return 0.0; // 避免除零

    double range = static_cast<double>(maximum() - minimum());
    double currentValue = static_cast<double>(value() - minimum());

    return (currentValue * 100.0) / range;
}

void CustomProgressBar::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        setProgressFromMousePosition(event->pos());
        event->accept();
    } else {
        QProgressBar::mousePressEvent(event);
    }
}

void CustomProgressBar::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        setProgressFromMousePosition(event->pos());
        event->accept();
    } else {
        QProgressBar::mouseMoveEvent(event);
    }
}

void CustomProgressBar::setProgressFromMousePosition(const QPoint &pos)
{
    QStyleOptionProgressBar option;
    initStyleOption(&option);

    QRect progressRect = style()->subElementRect(QStyle::SE_ProgressBarGroove, &option, this);
    QRect contentsRect = progressRect.adjusted(2, 2, -2, -2);

    if (contentsRect.isEmpty()) {
        contentsRect = rect().adjusted(2, 2, -2, -2);
    }

    int availableWidth = contentsRect.width();
    if (availableWidth <= 0) return;

    int clickPos = pos.x() - contentsRect.x();
    clickPos = qMax(0, qMin(clickPos, availableWidth));

    double percentage = (static_cast<double>(clickPos) / availableWidth) * 100.0;

    // 使用新的百分比设置接口
    setPercentage(percentage);

    emit progressClicked(value());
}
